/**
 * 
 */
package com.glela.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.glela.common.Base;
import com.glela.common.exception.BusinessError;
import com.glela.common.exception.BusinessException;
import com.glela.common.exception.PlatformException;
import com.glela.common.util.CastUtil;

/**
 * @author liujie 请求操作统一处理
 */
@Aspect
@Component
public class ActionAspect
{

	private static final Logger logger = LoggerFactory.getLogger(ActionAspect.class);

	/**
	 * 处理操作请求的输入输出日志、操作异常等
	 * 
	 * @param pjp
	 * @return
	 */
	@Around("@annotation(com.glela.common.annotation.AnActionLog)")
	public Object doo(ProceedingJoinPoint pjp)
	{
		String err = null;//error message
		Object retObj = null;//response data
		//log info
		String logInfo = " ==> " + pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName();
		try {
			//get request parameters
			String params = "";
			Object[] args = pjp.getArgs();
			if (args != null) {
				for (Object arg : args) {
//					if (arg instanceof IntegralRecordModel) {
//						params += JSON.toJSONString(arg);
//					}
//					else {
						params += arg.toString();
//					}
				}
			}
			//write input log
			logger.info(logInfo + " was invoked whith parameter: " + params);
			//action start
			retObj = pjp.proceed();
			//success
		}
		catch (Throwable e) {
			//system exception
			err = e.getMessage();
			String code = BusinessError.C20007.getCode();
			if (e instanceof PlatformException) {
				code = ((BusinessException) e).getBusinessError().getCode();
				if (BusinessError.C8888.getCode().equals(code) || BusinessError.C0001.getCode().equals(code)
						|| BusinessError.C0000.getCode().equals(code)) {
					BusinessError.C20007.getCode();
				}
				logger.info(err);
			}
			else {
				logger.error(err, e);
			}
			retObj = new ResponseEntity<Base>(new Base(CastUtil.castInt(code), err), HttpStatus.OK);
		}
		//write output log
		logger.info(logInfo + " was responded data: " + JSON.toJSONString(retObj));
		//response
		return retObj;
	}
}
